import router from '@/router'
import { useUserStore } from '@/stores/user'
import axios from 'axios'
import { showToast } from 'vant'

export const baseURL = 'https://consult-api.itheima.net/'
const instance = axios.create({
  baseURL,
  timeout: 10000
})

instance.interceptors.request.use(
  (config) => {
    const store = useUserStore()
    if (store.user?.token && config.headers) {
      config.headers.Authorization = `Bearer ${store.user.token}`
    }
    return config
  },
  (err) => Promise.reject(err)
)

instance.interceptors.response.use(
  (res) => {
    if (res.data.code !== 10000) {

      showToast(res.data.message || '失败了')

      return Promise.reject(res.data)
    }

    return res.data
  },
  (err) => {

    if (err.response?.status === 401) {

      const store = useUserStore()
      store.delUser()

      router.push({
        path: '/login',
        query: { returnUrl: router.currentRoute.value.fullPath }
      })
    }
    return Promise.reject(err)
  }
)

export default instance

export const request =(url,method = 'GET',submitData) => {

  return instance.request({
    url,
    method,
    [method.toUpperCase() === 'GET' ? 'params' : 'data']: submitData
  })
}
